
// Load the net module to create a tcp server.
var net = require('net'),
request=require("request"),
logger = require('smart-logger')(module),
mapping = require('./mapping').mapping;

// Setup a tcp server
var server = net.createServer(function (socket) {
  var datasource = mapping["default"];
  // Every time someone connects, tell them hello and then close the connection.
  socket.addListener("connect", function () {
    console.log("Connection from " + socket.remoteAddress);
   datasource = mapping[socket.remoteAddress] || datasource;
});

  socket.on("data", function(data){
  console.log("new data from "+socket.remoteAddress);    

var block={};
    block.data=data.toString();
    request.post({url:"http://smartdata.atosworldline.com/api/datasources/"+datasource+"/datas" ,body:JSON.stringify(block) , headers : {"Content-Type":"application/json"} } ,function(e,r,b){
      if(e) return socket.write(e);
      if(r.statusCode === 200) {
        socket.write(data);
      }else{
        socket.write("error with datasource "+datasource);
      }
    });
  });
});

exports.setup = function setup(){
  var newserver = server;
  return newserver;
};

exports.start = function start (port, host, readyCallback) {
  var app;
  console.log("starting the server! ");
  if(typeof port === "function") {
    readyCallback = port;
    host = conf.get("logs-server:server:host");
    port = conf.get("logs-server:server:port");
  }
  logger.debug("Re Start smart-logs-server on " + host + ":" + port);
  console.log(" LOG Start smart-logs-server on " + host + ":" + port);
  app = setup();
  app.listen(port, host, readyCallback);
};
